<template>
	<div>
		<use-table ref="tbl"></use-table>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">分类名称：</div>
					<el-input v-model="req.name" placeholder="请输入" class="search_input" @change="search" clearable>
					</el-input>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<div class="dflex_vertical_c">
					<div class="remark_txt el-icon-info margin_t_0 margin_l_15 h_initial">分类有子类或分类有商品不可删除</div>
				</div>
				<el-button class="add-btn pos_r padding0" icon="iconfont iconxinzeng" @click="toAdd">新增</el-button>
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas" row-key="_id"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
				<el-table-column prop="name" label="分类名称" width="200"></el-table-column>
				<el-table-column label="排序" width="200" align="center">
					<template slot-scope="scope">
						<el-input-number size="small" :min="1" v-model="scope.row.sort"
							@change="(newSort, oldSort) => sortChange(newSort, oldSort, scope.row)"
							@blur="scope.row.sort = parseInt(scope.row.sort)"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column prop="_id" label="分类ID" align="center" width="250"></el-table-column>
				<el-table-column label="图标" align="center">
					<template slot-scope="scope">
						<el-image class="headimg" :src="scope.row.img" :preview-src-list="scope.row.previewImgs"
							fit="cover"></el-image>
					</template>
				</el-table-column>
				<el-table-column label="状态" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" :content="scope.row.state == '禁用' ? '点击启用' : '点击禁用'"
							placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-switch v-model="scope.row.state" active-color="#ff6a6c" inactive-color="#bbb"
								active-value="启用" inactive-value="禁用" @change="stateChange(scope.row)"></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column prop="create_time" label="创建时间" align="center"></el-table-column>
				<el-table-column label="操作" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" content="编辑" placement="top" :hide-after="1000" :enterable="false"
							effect="light">
							<el-button circle size="medium" icon="el-icon-edit" class="table-btn"
								@click="toEdit(scope.row._id)"></el-button>
						</el-tooltip>
						<el-tooltip :open-delay="350" content="删除" placement="top" :hide-after="1000" :enterable="false"
							effect="light">
							<el-button circle size="medium" icon="el-icon-delete" class="table-btn"
								:disabled="scope.row.children.length > 0" @click="remove(scope.row._id)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
		</div>
	</div>
</template>

<script>
	const __name = 'wmzmall-goods-category';
	export default {
		data() {
			return {
				req: {
					page: 1,
					rows: 500,
					orderby: 'sort asc',
					name: '',
					loading: false
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				searchBtnLoading: false,
				sortLastTime: null
			};
		},
		methods: {
			async loadData(callback) {
				this.tableLoading = true;

				this.req.startWith = "pid == ''";
				if (this.req.name) {
					this.req.startWith = '/' + this.req.name + '/.test(name)';
				}

				await this.$db[__name].totree(this.req).then(res => {
					if (res.code == 200) {
						let datas = [];
						res.datas.forEach((row, idx) => {
							row.create_time = new Date(row.create_time).format();
							if (row.children && row.children.length > 0) {
								row.children.forEach(c => {
									c.previewImgs = [c.img];
									c.create_time = new Date(c.create_time).format();
								});
							}
							row.previewImgs = [row.img];
							if (row.pid && res.datas.find(x => x._id == row.pid)) {
								return;
							}
							datas.push(row);
						});
						this.tableDatas = datas;

						if (typeof callback === 'function') {
							callback();
						}
					}
					this.searchBtnLoading = false;
					this.tableLoading = false;
				});
			},
			search() {
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			toAdd() {
				uni.navigateTo({
					url: `/pages/goods/classify/goods_classify_add_edit?tab=添加分类`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			toEdit(id) {
				uni.navigateTo({
					url: `/pages/goods/classify/goods_classify_add_edit?id=${id}&tab=编辑分类`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			remove(id) {
				this.$confirm('此操作将永久删除该数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$func.wmzadmin
						.call('goods/classifyRemove', {
							id: id
						})
						.then(res => {
							if (res.code == 200) {
								this.$message({
									message: res.msg,
									type: 'success'
								});
								this.loadData();
								return
							}
							if (res.code == 100) {
								this.$message(res.msg);
								return;
							}

							this.$message.error(res.msg);
						});
				});
			},
			sortChange(newSort, oldSort, row) {
				if (!newSort) {
					this.$nextTick(() => {
						row.sort = oldSort;
					})
					return;
				}

				if (event && ['change', 'mouseup'].includes(event.type)) {
					this.sortUpdate(row);
					return;
				}

				if (this.sortLastTime !== null) {
					clearTimeout(this.sortLastTime)
				}

				this.sortLastTime = setTimeout(() => {
					this.sortUpdate(row)
				}, 500);
			},
			sortUpdate(row) {
				this.$db[__name].update(row._id, {
					sort: parseInt(row.sort)
				}).catch(() => {
					this.loadData();
				})
			},
			stateChange(row) {
				this.$db[__name].update(row._id, {
					state: row.state
				}).catch(() => {
					this.loadData();
				})
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
			}

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style></style>
